package emby.lang;

import emby.err.TypeError;
import emby.overload.OverloadDot;
import emby.overload.OverloadIndex;
import emby.overload.OverloadType;

/**
 * Represents an immutable array.
 * @author Justin
 */
public class EmbyArray extends EmbyObject implements OverloadIndex, OverloadDot, OverloadType {

	private final Object[] contents;
	public EmbyArray(int length){
		this(length, EmbyNull.Null);
	}
	public EmbyArray(int length, Object initialize){
		contents = new Object[length];
		for(int i = 0; i<contents.length; i++){
			contents[i] = initialize;
		}
	}

	public Object[] getContents(){
		return contents;
	}

	@Override
	public Object get_dot(int line, String o) {
		if (o.equals("length")){
			return contents.length;
		}
		else if (o.equals("javaArray")){
			return contents;
		}
		else{
			throw new TypeError(line,"Array has no attribute: "+o);
			//return null;
		}
	}

	@Override
	public void set_dot(int line, String o, Object new_value) {
		throw new TypeError(line,"Attemted to assign values to array stuffs. ");
	}

	@Override
	public Object get_index(int errline, Object o) {
		if (!(o instanceof Integer)){
			throw new TypeError(errline,"Arrays must be indexed by integers. "+o);
		}
		int i = (Integer)o;
		return contents[i];
	}

	@Override
	public void set_index(int errline, Object index, Object new_value) {
		if (!(index instanceof Integer)){
			throw new TypeError(errline,"Arrays must be indexed by integers");
		}
		int i = (Integer)index;
		contents[i]=new_value;
	}

	public String toString(){
		if(contents.length==0)return "{}";
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		for(int i = 0; i<contents.length-1;i++){
			if( contents[i]==null){
				sb.append("null, ");
			}else
			sb.append(contents[i].toString()+", ");
		}
		if( contents[contents.length-1]==null){
			sb.append("null}");
		}else
		sb.append(contents[contents.length-1].toString()+"}");
		return sb.toString();
	}
	@Override
	public Object operatorType(int line, Scope s) {
		return "array";
	}

}
